package net.xujialiang.XTestRPA.Service.RPA;

import net.xujialiang.XTestRPA.Entity.RPA.XRPAGroup;
import net.xujialiang.XTestRPA.Entity.RPA.XRPATask;
import net.xujialiang.XTestRPA.Enum.LogEnum;
import net.xujialiang.XTestRPA.Repository.RPA.RPAGroupRepository;
import net.xujialiang.XTestRPA.Repository.RPA.RPATaskRepository;
import net.xujialiang.XTestRPA.Service.XRPALogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.*;

@Service
public class XRPAGroupService {
    @Autowired
    RPAGroupRepository rpaGroupRepository;
    @Autowired
    RPATaskRepository rpaTaskRepository;
    @Autowired
    XRPALogService logService;

    /**
     * 新建分组
     * @param groupName 分组名称
     */
    public void createGroup(String groupName, String createAccount, String ttc) throws Exception {
        UUID uuid = UUID.randomUUID();
        XRPAGroup entity = XRPAGroup.builder()
                .groupName(groupName)
                .groupID(uuid.toString())
                .createAccount(createAccount)
                .mOrder(0)
                .createTime(new Timestamp(System.currentTimeMillis()))
                .ttc(ttc)
                .build();
        rpaGroupRepository.save(entity);

        logService.addLog(LogEnum.RPAGroup.getModule(), "新建分组", createAccount, ttc);
    }

    /**
     * 删除分组
     * @param id 分组ID
     */
    public void deleteGroup(int id, String ttc, String operator) throws Exception {
        Optional<XRPAGroup> entity = rpaGroupRepository.findById(id);
        if(entity.isEmpty()){
            throw new Exception("未查询到分组");
        }else{
            // 判断是否是该分组所在租户
            XRPAGroup group = entity.get();
            // 删除分组之前需要判断组内是否有其他环境，需要先移除组内所有环境才能删除
            if(group.getTtc().equals(ttc)){
                String guid = group.getGroupID();
                List<XRPATask> tasks = rpaTaskRepository.findAllByGroupIDAndTtc(guid, ttc);
                if(tasks.size()>0){
                    throw new Exception("分组下存在"+tasks.size()+"个任务, 无法删除，请先转移该分组下的所有任务。");
                }else{
                    rpaGroupRepository.delete(entity.get());
                    logService.addLog(LogEnum.RPAGroup.getModule(), "删除分组", operator, ttc);
                }
            }else{
                throw new Exception("无权限操作");
            }
        }
    }

    /**
     * 更新分组名称
     * @param id 分组ID
     * @param groupName 分组名称
     * @throws Exception
     */
    public void updateGroup(int id, String groupName, Integer mOrder, String ttc, String operator) throws Exception {
        Optional<XRPAGroup> ret = rpaGroupRepository.findById(id);
        if(ret.isEmpty()){
            throw new Exception("未查询到分组");
        }else{
            XRPAGroup entity = ret.get();
            if(entity.getTtc().equals(ttc)){
                entity.setGroupName(groupName);
                entity.setMOrder(mOrder);
                rpaGroupRepository.save(entity);
                logService.addLog(LogEnum.RPAGroup.getModule(), "更新分组信息:"+groupName, operator, ttc);
            }else{
                throw new Exception("无权限操作");
            }
        }
    }

    /**
     * 更新排序
     * @param newOrders 新的排序
     */
    public void updateOrder(Map<Integer, Integer> newOrders, String ttc, String operator) throws Exception {
        Object[] ids = newOrders.keySet().toArray();
        Arrays.stream(ids).mapToInt(t-> (int) t);
        ArrayList<Integer> list = new ArrayList(Arrays.asList(ids));

        List<XRPAGroup> groups = (List<XRPAGroup>) rpaGroupRepository.findAllById(list);

        boolean noPermission = false;
        for (int i = 0; i < groups.size(); i++) {
            XRPAGroup group = groups.get(i);
            if(group.getTtc().equals(ttc)){
                Integer newOrder = newOrders.get(group.getId());
                group.setMOrder(newOrder);
            }else{
                noPermission= true;
            }
        }
        if(noPermission) {
            throw new Exception("无权限操作");
        }else{
            rpaGroupRepository.saveAll(groups);
            logService.addLog(LogEnum.RPAGroup.getModule(), "更新分组排序:", operator, ttc);
        }

    }

    /**
     * 分页获取分组数据
     * @param page 页码
     * @param pageSize 每页条数
     * @return
     */
    public Map<String, Object> fetchGroupsByPage(String ttc, String groupName, int page, int pageSize) {
        Sort sort = Sort.by(Sort.Direction.DESC, "mOrder", "id");
        PageRequest pr =  PageRequest.of(page,pageSize, sort);
        if(groupName.equals("")){
            groupName = null;
        }
        Page<XRPAGroup> pageData = rpaGroupRepository.findAllByTtcAndGroupName(ttc, groupName, pr);
        Map<String, Object> ret = new LinkedHashMap<>();
        ret.put("totalPages", pageData.getTotalPages());
        ret.put("totalCount", pageData.getTotalElements());
        ret.put("page", page);
        ret.put("pageSize", pageSize);
        ret.put("list", pageData.getContent());
        return ret;
    }
}
